import { ModelRef, ref } from 'vue';
import { AddNodeType } from '../types';
import { Ref } from 'vue';

export function useNodeConfig<T extends AddNodeType>(model: ModelRef<T>) {
	const drawerVisible = ref(false);
	const isEditTitle = ref(false);
	const form = ref({}) as Ref<T>;
	const nodeConfig = ref({}) as Ref<T>;

	onMounted(() => {
		nodeConfig.value = model.value;
	});

	watch(
		() => model.value,
		() => {
			nodeConfig.value = model.value;
		}
	);

	function show() {
		form.value = JSON.parse(JSON.stringify(model.value));
		isEditTitle.value = false;
		drawerVisible.value = true;
	}

	const nodeTitleRef = ref();
	function editTitle() {
		isEditTitle.value = true;
		nextTick(() => {
			nodeTitleRef.value.focus();
		});
	}

	function save() {
		model.value = form.value;
		drawerVisible.value = false;
	}

	function delNode() {
		model.value = nodeConfig.value.childNode as T;
	}

	return {
		drawerVisible,
		isEditTitle,
		form,
		nodeConfig,
		nodeTitleRef,
		show,
		editTitle,
		save,
		delNode,
	};
}
